<?php
/**
 * (logic) （临时转正式）Payment退还
 */
namespace App\Logic\MonthlyReport\ParseTmp;

use App\Models\Basics\SysCountry;
use App\Models\MonthlyReport\Payment\PaymentRebates;
use App\Models\MonthlyReport\Tmp\TmpPSales;
class ParsePaymentRebates
{
    public static function exeParse($date){
        //临时
        $lines = TmpPSales::query()->selectRaw('country,sku,sum(IFNULL(promotional_rebates,0) + IFNULL(other_transaction_fees,0) + IFNULL(other,0)) as rebates')
            ->where('report_date',$date)
            ->whereNotNull('sku')
            ->groupBy(['country','sku'])
            ->get();
        $i = 0;
        $num = 500;
        $country = [];
        while(true){
            if($lines->isEmpty())break;
            $_lines = $lines->splice($i,$num);
            foreach ($_lines as $line){
                if(!array_key_exists($line->country,$country)){
                    $countryId = SysCountry::getIdByCountry($line->country);
                    $country[$line->country] = $countryId ?: 0;
                }
                //正式
                PaymentRebates::query()->updateOrCreate(['report_date' => $date,
                    'country_id' => $country[$line->country],
                    'seller_sku' => $line->sku],
                    ['rebates' => $line->rebates]);
            }
        }
    }
}
